package com.ruoyi.reservationserver.controller;

import com.ruoyi.reservationserver.entity.Knowledge;
import com.ruoyi.reservationserver.service.KnowledgeService;
import com.ruoyi.reservationserver.utils.Result;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * 体育知识表(Knowledge)表控制层
 *
 * @author makejava
 * @since 2023-07-04 16:21:48
 */
@RestController
@RequestMapping("knowledge")
public class KnowledgeController {
    /**
     * 服务对象
     */
    @Resource
    private KnowledgeService knowledgeService;

    /**
     * 分页查询
     *
     * @param knowledge 筛选条件
     * @param pageRequest      分页对象
     * @return 查询结果
     */
    @GetMapping
    public ResponseEntity<Page<Knowledge>> queryByPage(Knowledge knowledge, PageRequest pageRequest) {
        return ResponseEntity.ok(this.knowledgeService.queryByPage(knowledge, pageRequest));
    }

    /**
     * 获取运动常识列表
     * @return
     */
    @GetMapping("/getDynamic")
    public Result getDynamic(){

        List<Knowledge> knowledges = knowledgeService.list();
        if (knowledges.isEmpty()){
            return Result.error("不存在常识");
        }else {
            return Result.success(knowledges);
        }
    }

//    /**
//     * 获取动态新闻列表数量
//     * @return
//     */
//    @GetMapping("/getDynamicNum")
//    public Result getDynamicNum(){
//        Result result = new Result();
//        int count = dynamicService.count();
//        if (count <0){
//            return Result.error("500","错误");
//        }else {
//            return Result.success(count);
//        }
//    }


    /**
     * 新增数据
     *
     * @param knowledge 实体
     * @return 新增结果
     */
    @PostMapping("add")
    public Result add(@RequestBody Knowledge knowledge) {
        if (knowledge==null){
            return Result.error("数据不能为空。");
        }
        return Result.success(this.knowledgeService.insert(knowledge));
    }

    /**
     * 编辑数据
     *
     * @param knowledge 实体
     * @return 编辑结果
     */
    @PostMapping("/edit")
    public Result edit(@RequestBody Knowledge knowledge) {
//        System.out.println(dynamic);
        if (knowledge==null){
            return Result.error("返回数据不能为空");
        }
        this.knowledgeService.update(knowledge);
        return Result.success();
    }

    /**
     * 删除数据
     *
     * @param id 主键
     * @return 删除是否成功
     */
    @GetMapping("/del")
    public Result deleteById(@RequestParam("knowledgeId") Integer id) {

        try {

            if(this.knowledgeService.deleteById(id)){
                return Result.success();
            }else {
                return Result.error("删除失败");
            }

        }catch (Exception e) {
            System.out.println(e);
            return Result.error("删除异常");
        }

    }

}

